import React, { useImperativeHandle, forwardRef, useState, useRef } from 'react';
import { View, Text, StyleSheet, SafeAreaView, Modal, Image, TouchableOpacity, TouchableWithoutFeedback, TextInput } from 'react-native'
import { connect } from 'react-redux'
import { SetWalletNetworkListOpen } from "../../redux/features/walletSlice"
import { pTx } from "../../utils/dimensions"
import { useNavigation } from '@react-navigation/native';
import httpApi from "../../api"
import { grade } from "../../utils/grade"
import { ImagePreview, NavBar } from '@pingtou/rn-vant';
import { ListView } from '@ant-design/react-native'
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import ImageEquallyEnlarge from "../../components/imageEquallyEnlarge"
import ImageView from "react-native-image-viewing";


const mapState = state => {
    return {
    }
}

const AddModalWallet = React.forwardRef((props, ref) => {
    const [open, setOpen] = useState(false)
    const [openPostComment, setOpenPostComment] = useState(true)
    const [sendPostCommentLoading, setSendPostCommentLoading] = useState(false)
    const [comment, setComment] = useState("")
    const [images, setImages] = useState(0)
    const [imageIndex, setImageIndex] = useState(0)
    const [visible, setVisible] = useState("")


    const [item, setItem] = useState({})
    const listViewRefs = useRef(null)
    const textInputRefs = useRef(null)


    const navigation = useNavigation();
    const setcommunityDetails = (Item) => {
        setOpen(true)
        setItem(Item)
    }
    useImperativeHandle(ref, () => ({
        setcommunityDetails,
    }))

    onFetch = async (pageNum = 1, startFetch, abortFetch,) => {
        try {
            let pageSize = 10
            const res = await httpApi.getPostCommentList({ pageNum: (pageNum - 1), pageSize, postId: item.Id })
            startFetch(res.data.PostCommentList, pageSize)
        } catch (err) {
            abortFetch()
        }
    }

    textInputRefsfocus = () => {
        setOpenPostComment(true)
        setTimeout(() => {
            textInputRefs.current?.focus()
        }, 600)
    }

    sendPostComment = async () => {
        try {
            if (!sendPostCommentLoading) {
                setSendPostCommentLoading(true)
                const res = await httpApi.postComment({ postId: item.Id, comment: comment })
                if (res.code == 20) {
                    let rowData = listViewRefs.current.ulv.getRows();
                    rowData.push({
                        NickName: "我",
                        Comment: comment
                    })
                    listViewRefs.current.ulv.updateDataSource(rowData)
                    props.sendPostComment(item)
                }
            }

        } catch (error) {
        }
        setSendPostCommentLoading(false)
        setOpenPostComment(false)
        setComment("")
    }


    renderItem = (item, i) => {
        return (
            <View style={styles.renderItemli}>
                <Image style={styles.ProfilePhoto} source={{ uri: httpApi.inline + item.ProfilePhoto }}></Image>
                <View style={[styles.PostContainer, {
                    flex: 1,
                    borderBottomColor: "rgba(175,181,189,0.15)",
                    borderBottomWidth: 1,
                    paddingBottom: pTx(15)
                }]}>
                    <View style={styles.PostContainerUserInfo}>
                        <View style={styles.infoCotent}>
                            <Text style={styles.NickName}>{item.NickName}</Text>
                        </View>
                        <Text style={styles.timr, { fontSize: pTx(10) }}>{item.CreatedAt}</Text>
                    </View>
                    <View style={styles.ContentInfo, { paddingTop: pTx(3) }}>
                        <Text style={styles.Comment, { fontSize: pTx(12) }}>{item.Comment}</Text>
                    </View>
                </View>

            </View>
        )
    }

    renderHeader = () => {
        return (
            <>
                <View style={styles.renderItemli}>
                    <Image style={styles.ProfilePhoto} source={{ uri: httpApi.inline + item.ProfilePhoto }}></Image>
                    <View style={styles.PostContainer}>
                        <View style={styles.PostContainerUserInfo}>
                            <View style={styles.infoCotent}>
                                <Text style={styles.NickName}>{item.NickName}</Text>
                                <Image style={styles.infoCotentImage} source={grade[item.UserLevel]}></Image>
                            </View>
                            <Text style={styles.timr}>{item.CreatedAt}</Text>
                        </View>
                        <View style={styles.ContentInfo}>
                            {item.Content ? <Text style={styles.Content}>{item.Content}</Text> : ""}
                            {item.Image ?
                                <View style={styles.ContentImageList}>
                                    {
                                        item.Image?.split(',').map((img, i) => {
                                            let image = item.Image?.split(',').map(item => { return { uri: httpApi.inline + item } })
                                            const length = image.length
                                            return (
                                                <TouchableWithoutFeedback
                                                    key={i}
                                                    onPress={() => {
                                                        setImages(image)
                                                        setImageIndex(i)
                                                        setVisible(true)
                                                    }}
                                                >
                                                    <View>
                                                        {
                                                            length == 1 ?
                                                                <ImageEquallyEnlarge
                                                                    source={{ uri: httpApi.inline + img }}
                                                                    width={pTx(220)}
                                                                />
                                                                :
                                                                <Image
                                                                    style={[styles.ContentImageItem]}
                                                                    source={{ uri: httpApi.inline + img }}></Image>
                                                        }
                                                    </View>
                                                </TouchableWithoutFeedback>
                                            )
                                        })
                                    }
                                </View>
                                : ""}
                        </View>

                        <View style={styles.CommentsQuantityObx}>
                            <View style={styles.CommentsQuantityObxCell}>
                                <Image style={styles.CommentsIcon} source={require('../../assets/image/icon16.png')}></Image>
                                <Text style={styles.postCommentValue}>{item.Likes}</Text>
                            </View>

                            <TouchableOpacity onPress={() => this.textInputRefsfocus()}>
                                <View style={styles.CommentsQuantityObxCell}>
                                    <Image style={styles.CommentsIcon} source={require('../../assets/image/icon17.png')}></Image>
                                    <Text style={styles.postCommentValue}>{item.Comments}</Text>
                                </View>
                            </TouchableOpacity>
                            <View style={styles.CommentsQuantityObxCell}>
                                <Image style={styles.CommentsIcon} source={require('../../assets/image/icon18.png')}></Image>
                                <Text style={styles.postCommentValue}>{item.Favorites}</Text>
                            </View>
                        </View>
                    </View>
                </View>
                <Text style={styles.CommentText}>评论</Text>
                <ImageView
                    images={images}
                    imageIndex={imageIndex}
                    visible={visible}
                    onRequestClose={() => setVisible(false)}
                />
            </>
        )
    }

    return (
        <Modal
            visible={open}
            animationType="fade"
            onRequestClose={() => {
                setOpen(false)
            }}
            transparent={true}>
            <SafeAreaView style={styles.ModalBox}>
                <View style={styles.NavBar}>
                    <View style={styles.onPressLeft}>
                        <TouchableOpacity onPress={() => setOpen(false)}>
                            <IconOutline style={styles.NavBarIcon} name="left" />
                        </TouchableOpacity>
                    </View>
                    <Text style={styles.NavBarTitle} >
                        详情
                    </Text>
                    <IconOutline style={styles.NavBarIcon} name="ellipsis" />
                </View>

                <ListView
                    ref={listViewRefs}
                    header={this.renderHeader}
                    onFetch={onFetch}
                    keyExtractor={(item, index) => `${index} - ${item}`}
                    renderItem={renderItem}
                    numColumns={1}
                />
                <View style={styles.TextInputObxBlock}>
                    <View style={styles.TextInputObx}>
                        {/* <IconFont name="cross" size={pTx(30)} color="#333" style={styles.cross} onPress={() => this.setState({ openPostComment: false })} /> */}
                        <TextInput
                            ref={textInputRefs}
                            type={'text'}
                            rows={1}
                            multiline={true}
                            value={comment}
                            style={styles.textInputRefs}
                            onBlur={() => setOpenPostComment(false)}
                            onChangeText={value => setComment(value)}
                        >
                        </TextInput>
                        <TouchableOpacity onPress={this.sendPostComment}>
                            <Text style={styles.send}>发送</Text>
                        </TouchableOpacity>
                    </View>
                </View>

            </SafeAreaView>
        </Modal>
    );
})

export default connect(mapState, { SetWalletNetworkListOpen }, null, { forwardRef: true })(AddModalWallet)

const styles = StyleSheet.create({
    NavBar: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between"
    },
    NavBarTitle: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    onPressLeft: {
    },
    NavBarIcon: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(15),
        textAlign: "right",
        fontSize: pTx(18),
        color: "#0A0C14",
        fontWeight: "500"
    },
    ModalBox: {
        position: "relative",
        flex: 1,
        backgroundColor: "#fff",
    },
    container: {

    },

    renderItemli: {
        marginTop: pTx(16),
        flexDirection: 'row',
        paddingHorizontal: pTx(15),
    },
    ProfilePhoto: {
        width: pTx(41),
        height: pTx(41),
        backgroundColor: "#EDEDED",
        borderRadius: pTx(4),
    },
    PostContainer: {
        marginLeft: pTx(8),
    },
    PostContainerUserInfo: {

    },
    infoCotent: {
        flexDirection: 'row',
        alignItems: "center"
    },
    infoCotentImage: {
        width: pTx(34),
        height: pTx(16),
    },
    NickName: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    timr: {
        marginTop: pTx(7),
        fontSize: pTx(12),
        color: "#AFB5BD",
    },
    ContentInfo: {
        marginTop: pTx(13),
        maxWidth: pTx(290)
    },
    Content: {
        fontSize: pTx(15),
        color: "#0A0C14"
    },
    ContentImageList: {
        marginTop: pTx(8),
        flexDirection: 'row',
        flexWrap: "wrap",
        width: pTx(290)
    },
    ContentImageItem: {
        width: pTx(90),
        height: pTx(90),
        marginRight: pTx(5),
        marginBottom: pTx(5),
        borderRadius: pTx(4),
        backgroundColor: "#EDEDED",
    },
    postComment: {
        marginTop: pTx(10),
        width: pTx(296),
        paddingVertical: pTx(6),
        backgroundColor: "rgba(237,237,237,0.3)",
        borderRadius: pTx(3),
    },
    postCommentCell: {
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(6),
        fontSize: pTx(14),
        color: "#0A0C14"
    },
    CommentsQuantityObx: {
        marginTop: pTx(12),
        paddingBottom: pTx(16),
        flexDirection: 'row',
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1,
    },
    CommentsQuantityObxCell: {
        flexDirection: 'row',
        alignItems: "center",
        marginRight: pTx(32),
    },
    CommentsIcon: {
        marginRight: pTx(3),
        width: pTx(14),
        height: pTx(14),
        padding: pTx(1),
    },
    postCommentValue: {
        fontSize: pTx(10),
        color: "#A6A8B3"
    },
    CommentText: {
        fontSize: pTx(16),
        color: "#0A0C14",
        paddingVertical: pTx(15),
        paddingHorizontal: pTx(15),
    },

    TextInputObxBlock: {
    },
    TextInputObx: {
        backgroundColor: "#EDEDED",
        position: "relative",
        flexDirection: "row",
        alignItems: "flex-end",
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
        // paddingTop: pTx(10),
        // marginBottom: pTx(20),
    },
    send: {
        marginHorizontal: pTx(5),
        marginBottom: pTx(3),
        height: pTx(30),
        paddingHorizontal: pTx(12),
        fontSize: pTx(14),
        color: "#fff",
        backgroundColor: "rgba(6, 193, 97, 1)",
        borderRadius: pTx(4),
        textAlignVertical: "center"
    },
    textInputRefs: {
        flex: 1,
        marginHorizontal: pTx(5),
        paddingHorizontal: pTx(5),
        paddingVertical: 0,
        minHeight: pTx(36),
        maxHeight: pTx(105),
        fontSize: pTx(14),
        backgroundColor: "#fff",
        borderRadius: pTx(4),
    },
    releaseImage: {
        width: pTx(74),
        height: pTx(74),
    },
})